package com.demo; /**
 * @author wzm
 * @create 2023-06-30 10:31
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;chatset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //获取记住我
        String remember = request.getParameter("remember");


        if("zs".equals(username) && "123456".equals(password)){
            //判断是否需要记住
            if("1".equals(remember)){
                System.out.println("remember = " + remember);
                //勾选 存储的登录信息
                Cookie uname = new Cookie("username",username);
                Cookie pwd = new Cookie("password",password);

                uname.setMaxAge(60*60*24*7);
                pwd.setMaxAge(60*60*24*7);

                response.addCookie(uname);
                response.addCookie(pwd);
            }

            //登录成功
            request.getSession().setAttribute("loginUser",username);
            //跳转到首页
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            request.setAttribute("msg","登录失败，用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }
}
